<?php


namespace app\model;


use think\Model;

class Admin extends Model
{
    /**
     * @param string $username 用户名
     * @param string $password 密码
     * @param int $type 判断类别
     * @return array|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login(string $username, string $password, $type = 1)
    {
        $map = [];
        switch ($type) {
            case 1:
                $map['username'] = $username;
                break;
            case 2:
                $map['email'] = $username;
                break;
            case 3:
                $map['mobile'] = $username;
                break;
            case 4:
                $map['id'] = $username;
                break;
            default:
                return 0; //参数错误
        }

        /* 获取用户数据 */
        $user = self::where($map)->find();
        if ($user) {
            /* 验证用户密码 */
            if (ucenter_encrypt_md5($password, $user['salt']) === $user['password']) {
                $returnData = [
                    'ret' => true,
                    'username' => $user['username'],
                    'id' => $user['id'],
                    'last_login_time' => time()
                ];

                // 自动登录用户
                $this->autoLogin($returnData);

                return $returnData; //登录成功，返回用户ID
            } else {
                return -2; //密码错误
            }
        } else {
            return -1; //用户不存在或被禁用
        }
    }
}